package com.hsj.common.gateway.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName : ExecutorConfig
 * @Description : 线程池配置文件
 * @Author : 康仕球
 * @Date: 2022-01-27 22:58
 */
@Configuration
@EnableAsync
public class ExecutorConfig {

    @Value("${thread.corePoolSize}")
    private int corePoolSize;

    @Value("${thread.maximumPoolSize}")
    private int maximumPoolSize;

    @Value("${thread.keepAliveTime}")
    private int keepAliveTime;

    @Value("${thread.workQueue}")
    private int workQueue;

    private static final String threadNamePrefix = "Async-Server-gateway-";


    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getMarketAsyncExcetor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数
        executor.setMaxPoolSize(maximumPoolSize);
        // 允许线程空闲时间（单位：默认秒）
        executor.setKeepAliveSeconds(keepAliveTime);
        // 缓冲队列数
        executor.setQueueCapacity(workQueue);
        // 线程池名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();
        return executor;
    }

}
